package syncer

import (
	"context"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/xiyoufang/cloud-syncer/internal/log"
	"os"
)

type S3Syncer struct {
	bucketName string
	client     *s3.Client
	logger     *log.Logger
}

func NewS3Syncer(accessKeyId, secretAccessKey, bucketName, region string, logger *log.Logger) (Syncer, error) {
	cfg, err := config.LoadDefaultConfig(context.Background(),
		config.WithRegion(region),
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyId, secretAccessKey, "")))
	if err != nil {
		return nil, err
	}
	client := s3.NewFromConfig(cfg)
	return &S3Syncer{
		client:     client,
		bucketName: bucketName,
		logger:     logger,
	}, nil
}

func (s *S3Syncer) PushFile(local string, remote string) error {
	file, err := os.Open(local)
	if err != nil {
		return err
	}
	defer file.Close()
	fileInfo, _ := file.Stat()
	fileSize := fileInfo.Size()
	_, err = s.client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket:        aws.String(s.bucketName),
		Key:           aws.String(remote),
		Body:          file,
		ContentLength: aws.Int64(fileSize),
	})
	if err != nil {
		return err
	}
	return nil
}
